from typing import Dict, List

from . import DEFAULT_MODEL_NAME, Prompt, client

SYSTEM_PROMPT = """{role_prompt}
你的任务是澄清意图。
举例说明：
{clarify}

{exclusion_block}
"""

USER_PROMPT = """市民已经提供的具体情况如下
{context}
用户具体要办理的事项似乎不完整，需要你根据需要区分的情况，询问用户进行要素补全。注意每次只要求用户补全一个要素信息，直接询问，简短直接。
需要区分的情况：
{candidates}
请你反问用户，澄清用户的具体意图，如果用户的意图属于例外情况，请你按照要求直接回复用户，不需要澄清。
"""


def build_prompt(
    clarify: List[str], candidates: List[str], context: str, role_prompt: str, exclusion: List[Dict] = None
) -> "Prompt":
    # Build exclusion block
    exclusion_lines: List[str] = []
    if exclusion:
        exclusion_lines.append("另外，下列例外情况类别无需澄清，请按类别自然回复：")
        for item in exclusion:
            category = item.get("category") if isinstance(item, dict) else getattr(item, "category", None)
            examples = item.get("examples") if isinstance(item, dict) else getattr(item, "examples", [])
            definition = item.get("definition") if isinstance(item, dict) else getattr(item, "definition", None)
            words = item.get("words") if isinstance(item, dict) else getattr(item, "words", [])
            
            if category:
                # Build a more natural description for each category
                category_desc = f"**{category}**"
                
                if definition:
                    # Clean up definition formatting and add it naturally
                    clean_definition = definition.strip().replace('\n', ' ')
                    category_desc += f"：{clean_definition}"
                
                if examples and len(examples) > 0:
                    examples_str = "、".join(examples)
                    category_desc += f" 例如：{examples_str}。"
                elif definition:
                    category_desc += "。"
                
                if words and len(words) > 0:
                    # Use the first response template as the main one
                    main_response = words[0] if isinstance(words[0], str) else str(words[0])
                    category_desc += f" 建议回复：{main_response}"
                
                exclusion_lines.append(f"- {category_desc}")
    exclusion_block = ("\n" + "\n".join(exclusion_lines)) if exclusion_lines else ""
    
    system_prompt = SYSTEM_PROMPT.format(
        clarify="\n\n".join(clarify), role_prompt=role_prompt, exclusion_block=exclusion_block
    )
    user_prompt = USER_PROMPT.format(
        context=context, 
        candidates="\n".join(candidates),
    )
    return Prompt(system_prompt=system_prompt, user_prompt=user_prompt)


async def run_agent(
    clarify: List[str], candidates: List[str], context: str, role_prompt: str, exclusion: List[Dict] = None
) -> str:
    """Run the agent.

    Args:
        clarify: The clarify.
        candidates: The candidates.
        context: The context.
    """
    prompt = build_prompt(clarify, candidates, context, role_prompt, exclusion=exclusion)
    chat_completion = await client.chat.completions.create(
        messages=[
            {"role": "system", "content": prompt.system_prompt},
            {"role": "user", "content": prompt.user_prompt},
        ],
        model=DEFAULT_MODEL_NAME,
    )
    # get response str
    response = chat_completion.choices[0].message.content
    return response
